function Promise(executor) {
  let self = this
  // 保存成功的值和失败的原因
  self.value = undefined
  self.reason = undefined
  // 专门保存成功的回调
  self.onResolvedCallbacks = []
  // 专门保存失败的回调
  self.onRejectedCallbacks = []
  // 保存当前这个promise的状态(3个状态pending、resolved，rejected)
  self.status = 'pending'
  function resolve(value) {
    if(self.status === 'pending') {
      self.value = value
      self.status = 'resolved'
      self.onResolvedCallbacks.forEach(fn => {
        fn()
      });
    }
  }
  function reject(reason) {
    if(self.status === 'pending') {
      self.reason = reason
      self.status = 'rejected'
      self.onRejectedCallbacks.forEach(fn => {
        fn()
      });
    }
  }
  // executor是立即执行的
  executor(resolve, reject)
}
// then方法的实现
Promise.prototype.then = function(onFulfilled, onRejected) {
  let self = this
  if(self.status === 'resolved') {
    onFulfilled(self.value)
  }
  if(self.status === 'rejected') {
    onRejected(self.reason)
  }
// executor中有一部操作，此时调用then时，处于等待状态
  if(self.status === 'pending') {
    self.onResolvedCallbacks.push(function(){
      onFulfilled(self.value)
    })
  }
  if(self.status === 'pending') {
    self.onRejectedCallbacks.push(function(){
      onRejected(self.reason)
    })
  }
}

module.exports = Promise